﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Dillon.Security;
using Views.Properties;

namespace Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        string GetLocalInfo()
        {



            return string.Format("Mac:{0};CpuID:{1};HardID:{2}",
              Local.GetLocalMac(),
              Local.GetCpuID(),
              Local.GetHardID());
        }

        /// <summary>
        /// 对原始数据进行MD5加密
        /// </summary>
        /// <param name="m_strSource">待加密数据</param>
        /// <returns>返回机密后的数据</returns>
        public string GetHash(string m_strSource)
        {

            HashAlgorithm algorithm = HashAlgorithm.Create("MD5");

            byte[] bytes = Encoding.UTF8.GetBytes(m_strSource);

            byte[] inArray = algorithm.ComputeHash(bytes);

            return Convert.ToBase64String(inArray);

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //2BDD0ABBFFD36587DD20D1C17ED89BBB103E9E9770E763D17A4CF73B4AB21865C2A4CDCD842BAF2092E21F195533AF2EDF3E6B9262A3EA5F06D341D43AEF8E5AAC6B4AD5A7BF4EE2F82F363202D51752B4F087AA848C70287219D7D97CF71FD01D73E9B9A2D87DDC1CF3AF9C2E9FAAF3D5D9CA50632106C7A3D8B3C478EF1E16-2665B408A15892C87A5D4F0005097D0F4E4A7D49742FF38749D3ADFCE15FE0619FFA56E47D91E54F22613D8DCF43A639D1A308223D6D62A3D8BA57038BF8C432737712D8A57E1E4F7E768448E09DC6A8B3EBE96A1166414080C7D7F2672304B92F81B7C1747048AC04B105C9F706478222CF3C4D9587824F2DFFD20AF75482B2-cnolrQKwa+kemfDxSIA/hFa0slWd/snMB+zUhcjmnGQ/HhgF0nTTds7sJ9FnwAtTMqK1YgfkmYyHeaIgXlFUxX09/ahnSrhQb7hvbAqUC3WqfFad9yIA+A==
            //78125C3F1EB91E50C3501AC4AB8F4D03475BDBD6CE981CC17291F379D799221817CCB37C44A4D93A3239D2115ECDFCBA5DE4D3B90B73032CEEDE8299226B81E69CD51EE04DB0B755A1F9A80B036A2E97D78C79C70B8AA3A30742917EDAC4F349262E42E0E1CCC4FF4F9780158366FFAA1827CCFF5BBC7E849EAE44FEB75193AC-71B927ABBE1BA643B92FF813F464713D30930A5AF9022F79AE27B0B03F7415D3B6620A98AAD13636D212EEF0D63F5E0C286DC6DB8126AEA1ECA8845F485E17D09EFCB9BAE52ADA390582AFF0FC700F3FE4E60CDB1D92393E6AFB8A06F6BFD63900BDB55A8FC37DCFA15812A21B13C03256534435DD3AC66D6A99F587586A71E4-kBbXn1WBubq1vPiideUoBqRKdFZf2RHYea9kSG5zuPsqzRw8tNC/5rqxE4dvd1Vo6zmoqWSsnwrcJtBkYKbh2r6C2Cacs8GW6WX7JZpi37n74Ekd8z9YMA==
            using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(1024))
            {
                this.privateKey.Text = this.FormatXml(rsa.ToXmlString(true));


                this.publicKey.Text = this.FormatXml(rsa.ToXmlString(false));
            }
        }

        string FormatXml(string xml)
        {
            var xmlContext = new StringBuilder();
            using (System.Xml.XmlWriter w = System.Xml.XmlWriter.Create(xmlContext, new System.Xml.XmlWriterSettings()
                {
                    NewLineChars = Environment.NewLine,
                    Indent = true,

                }
                    ))
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(xml);
                doc.WriteTo(w);
                w.Flush();
                return xmlContext.ToString();
            }
        }

        private void Button_EncryptByPrivateKey(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.privateKey.Text)
               || string.IsNullOrWhiteSpace(this.publicKey.Text))
            {
                MessageBox.Show("密钥对必须输入。");
                return;
            }

            this.encryptContext.Text = "";
            this.encryptContext2.Text = "";
            this.decryptContext.Text = "";
            this.decryptContext2.Text = "";

            {
                System.Security.Cryptography.RSACryptoServiceProvider p = new System.Security.Cryptography.RSACryptoServiceProvider();
                p.FromXmlString(this.privateKey.Text);
                var ep = p.ExportParameters(true);

                var d = Convert.ToBase64String(ep.D);
                var n = Convert.ToBase64String(ep.Modulus);
                this.encryptContext.Text = RC2RSA.Encrypt(this.GetClientAuthorization(), d, n);
                this.encryptContext2.Text = this.encryptContext.Text;
            }

            {

                System.Security.Cryptography.RSACryptoServiceProvider p = new System.Security.Cryptography.RSACryptoServiceProvider();
                p.FromXmlString(this.publicKey.Text);
                var ep = p.ExportParameters(false);
                var exponent = Convert.ToBase64String(ep.Exponent);
                var n = Convert.ToBase64String(ep.Modulus);
                this.decryptContext.Text = RC2RSA.Decrypt(this.encryptContext2.Text, exponent, n);
            }

        }

        private string GetClientAuthorization()
        {

            StringBuilder authorizationBuilder = new StringBuilder();
            authorizationBuilder.AppendFormat("ClientIdentity:{0}", this.clientIdentity.Text).AppendLine();
            authorizationBuilder.AppendFormat("FromDate:{0}", this.fromDate.SelectedDate.Value.ToString("yyyy/MM/dd")).AppendLine();
            authorizationBuilder.AppendFormat("ToDate:{0}", this.toDate.SelectedDate.Value.ToString("yyyy/MM/dd")).AppendLine();
            return authorizationBuilder.ToString();
        }



        private void Button_EncryptByPublicKey(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.privateKey.Text)
              || string.IsNullOrWhiteSpace(this.publicKey.Text))
            {
                MessageBox.Show("密钥对必须输入。");
                return;
            }

            System.Security.Cryptography.RSACryptoServiceProvider p = new System.Security.Cryptography.RSACryptoServiceProvider();
            p.FromXmlString(this.publicKey.Text);
            var ep = p.ExportParameters(false);

            var exponent = Convert.ToBase64String(ep.Exponent);
            var n = Convert.ToBase64String(ep.Modulus);
            this.encryptContext.Text = RC2RSA.Encrypt(this.GetClientAuthorization(), exponent, n);
            this.encryptContext2.Text = this.encryptContext.Text;
        }


        private void Button_DecryptByPublicKey(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.publicKey.Text))
            {
                MessageBox.Show("公钥必须输入。");
                return;
            }
            System.Security.Cryptography.RSACryptoServiceProvider p = new System.Security.Cryptography.RSACryptoServiceProvider();
            p.FromXmlString(this.publicKey.Text);
            var ep = p.ExportParameters(false);

            var exponent = Convert.ToBase64String(ep.Exponent);
            var n = Convert.ToBase64String(ep.Modulus);
            this.decryptContext2.Text = RC2RSA.Decrypt(this.encryptContext2.Text, exponent, n);
        }

        private void Button_DecryptByPrivateKey(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.privateKey.Text)
              || string.IsNullOrWhiteSpace(this.publicKey.Text))
            {
                MessageBox.Show("密钥对必须输入。");
                return;
            }
            System.Security.Cryptography.RSACryptoServiceProvider p = new System.Security.Cryptography.RSACryptoServiceProvider();
            p.FromXmlString(this.privateKey.Text);
            var ep = p.ExportParameters(true);

            var d = Convert.ToBase64String(ep.D);
            var n = Convert.ToBase64String(ep.Modulus);
            this.decryptContext2.Text = RC2RSA.Decrypt(this.encryptContext2.Text, d, n);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            this.privateKey.Text = Settings.Default.PrivateKey;
            this.publicKey.Text = Settings.Default.PublicKey;

            this.clientIdentity.Text = this.GetHash(this.GetLocalInfo());
            this.oneMonth.IsSelected = true;

        }


        private void ComboBoxItem_SelectedOneMonth(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(1);
        }

        int autoSetedMonthRange;
        bool isAutoSettingFlg = false;
        void SetDateRange(int monthRange)
        {
            this.isAutoSettingFlg = true;
            try
            {
                this.autoSetedMonthRange = monthRange;
                if (this.autoSetedMonthRange == 0)
                {
                    this.isAutoSettingFlg = false;
                    return;
                }
                if (!this.fromDate.SelectedDate.HasValue)
                {
                    var date = DateTime.Now.Date;
                    this.fromDate.SelectedDate = date;
                }
                if (monthRange >= 6)
                {
                    this.toDate.SelectedDate = this.fromDate.SelectedDate.Value.AddMonths(monthRange);
                }
                else
                {
                    this.toDate.SelectedDate = this.fromDate.SelectedDate.Value.AddDays(monthRange * 30);
                }
                this.isAutoSettingFlg = false;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                this.isAutoSettingFlg = false;
            }

        }

        private void ComboBoxItem_SelectedTwoMonth(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(2);
        }

        private void ComboBoxItem_SelectedThreeMonth(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(3);
        }

        private void ComboBoxItem_SelectedFourMonth(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(4);
        }

        private void ComboBoxItem_SelectedFiveMonth(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(5);
        }

        private void ComboBoxItem_SelectedHalfYear(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(6);
        }

        private void ComboBoxItem_SelectedOneYear(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(12);
        }

        private void ComboBoxItem_SelectedCustomer(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(0);
        }

        private void fromDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.isAutoSettingFlg || this.fromDate.SelectedDate == null || this.autoSetedMonthRange == 0)
            {
                return;
            }
            this.SetDateRange(this.autoSetedMonthRange);
        }

        private void toDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.isAutoSettingFlg || this.toDate.SelectedDate == null || this.autoSetedMonthRange == 0)
            {
                return;
            }
            this.isAutoSettingFlg = true;

            try
            {
                this.fromDate.SelectedDate = this.toDate.SelectedDate.Value.AddMonths(this.autoSetedMonthRange);
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                this.isAutoSettingFlg = false;
            }
        }

        private void privateKey_LostFocus(object sender, RoutedEventArgs e)
        {

            Settings.Default.PrivateKey = this.privateKey.Text;
            Settings.Default.Save();
        }

        private void publicKey_LostFocus(object sender, RoutedEventArgs e)
        {
            Settings.Default.PublicKey = this.publicKey.Text;
            Settings.Default.Save();
        }

        private void ComboBoxItem_SelectedTwoYear(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(24);

        }

        private void ComboBoxItem_SelectedFiveYear(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(60);

        }

        private void ComboBoxItem_SelectedTenYear(object sender, RoutedEventArgs e)
        {
            this.SetDateRange(120);
        }


    }
}
